#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2019
# @Author  : linhu (hlf0312@gmail.com)
# @Link    : TBD
# @Version : $Id$

# https://jiradc.int.net.nokia.com/rest/api/2/issue/FPB-247361
from jira import JIRA
from openpyxl import Workbook
from time import strftime, localtime
from FeatureBuildsSchedule import buildFeatureBuildsTimeline, getCurrentFB


class UserJiraIssues(object):
    """docstring for UserJiraIssues"""
    def __init__(self, userName, startDate, endDate):
        super(UserJiraIssues, self).__init__()
        self.userName = userName
        self.timeRemaining = 0
        self.loggedEfforts = 0
        self.jiraIssues = []
        self.startDate = startDate
        self.endDate = endDate

    def getTimeRemaining(self):
        return self.timeRemaining

    def getLoggedEfforts(self):
        return self.loggedEfforts

    def getJiraIssues(self):
        return self.jiraIssues

    def addJiraIssues(self, jiraIssue):
        self.jiraIssues.append(jiraIssue)
        self.timeRemaining += int(jiraIssue.fields.customfield_39192[:-1])
        for worklog in jiraIssue.fields.worklog.worklogs:
            if worklog.updated[:10] >= self.startDate and worklog.updated[:10] <= self.endDate:
                # print(worklog.timeSpentSeconds/3600, worklog.updated)
                self.loggedEfforts += worklog.timeSpentSeconds/3600



class LoggedEffortsAndTimeRemainingPersons(object):
    """docstring for LoggedEffortsAndTimeRemainingPersons"""
    def __init__(self, users, sprint):
        super(LoggedEffortsAndTimeRemainingPersons, self).__init__()
        self.users = users
        self.startDate = ''
        self.endDate = ''
        self.loggedEfforts = 0
        self.timeRemaining = 0
        self.sprint = sprint

    def setDateRange(self, startDate, endDate):
        self.startDate = startDate
        self.endDate = endDate

    def getJiraIssues(self, filter='assignee'):
        users = '('
        for user in self.users:
            users += user
            users += ','
        users = users[:-1]
        users += ')'
        # print(users)
        print('startDate: %s, endDate: %s' %(self.startDate, self.endDate))
        if filter == 'assignee':
            issues = jira.search_issues('assignee in ' + users +' AND project = LTE AND type=sub-task \
            AND (updatedDate >= ' + self.startDate + ' AND updatedDate <= ' + self.endDate + ')' + ' ORDER BY assignee ASC', \
            maxResults=300)
        elif filter == 'sprint':
            issues = jira.search_issues('Sprint in ' + '(' + self.sprint + ')' + ' AND type = Sub-task ORDER BY assignee ASC', \
            maxResults=300)
        else:
            print('Not supported filter, use assignee')
            issues = jira.search_issues('assignee in ' + users +' AND project = LTE AND type=sub-task \
            AND (updatedDate >= ' + self.startDate + ' AND updatedDate <= ' + self.endDate + ')' + ' ORDER BY assignee ASC', \
            maxResults=300)

        return issues

    def getLoggedEffortsAndTimeRemaining(self):
        issues = self.getJiraIssues(filter='sprint')
        for issue in issues:
            jiraIssue = jira.issue(issue.key)
            assigneeName = 'unassigned'
            if jiraIssue.fields.assignee:
                assigneeName = jiraIssue.fields.assignee.name
            if assigneeName in jiraIssuesCollection:
                jiraIssuesCollection[assigneeName].addJiraIssues(jiraIssue=jiraIssue)
            else:
                userJiraIssues = UserJiraIssues(userName=assigneeName, startDate=currentFBStartDate, endDate=currentFBEndDate)
                userJiraIssues.addJiraIssues(jiraIssue=jiraIssue)
                jiraIssuesCollection[assigneeName] = userJiraIssues
            if assigneeName != 'unassigned':
                self.timeRemaining += int(jiraIssue.fields.customfield_39192[:-1])
            # print(self.timeRemaining)
            for worklog in jiraIssue.fields.worklog.worklogs:
                if worklog.updated[:10] >= currentFBStartDate and worklog.updated[:10] <= currentFBEndDate:
                    # print(worklog.timeSpentSeconds/3600, worklog.updated)
                    self.loggedEfforts += worklog.timeSpentSeconds/3600

        return (self.timeRemaining, self.loggedEfforts)

today = strftime("%Y-%m-%d", localtime())
# now = datetime.now()
# today = '{:0>2s}'.format(str(now.year)) + '-' + '{:0>2s}'.format(str(now.month)) + '-' + '{:0>2s}'.format(str(now.day))
# print(today)

featureBuilds = buildFeatureBuildsTimeline()
currentFB = getCurrentFB(today, featureBuilds)
currentFBStartDate = currentFB.getStartDate()
currentFBEndDate = currentFB.getEndDate()
# print('current FB is %s' %currentFB.getFB())

options = {
    'server': 'https://jiradc.int.net.nokia.com'
    }

jira = JIRA(options, basic_auth=('xxx', 'xxx@yyy'))

userListFTH7=['wowu', 'moralesc', 'nifan', 'dahu', 'taoshi', 'fihuang', 'kshu']
sprintCPFTH7FB1906='51595'
jiraIssuesCollection = {}

loggedEffortsAndTimeRemainingPersons = LoggedEffortsAndTimeRemainingPersons(users=userListFTH7, sprint=sprintCPFTH7FB1906)
loggedEffortsAndTimeRemainingPersons.setDateRange(startDate=currentFBStartDate, endDate=currentFBEndDate)
personsTimeRemaining, personsLoggedEfforts = loggedEffortsAndTimeRemainingPersons.getLoggedEffortsAndTimeRemaining()
print('persons level: (personsTimeRemaining %sh, personsLoggedEfforts %sh)' %(personsTimeRemaining, personsLoggedEfforts))

for user in jiraIssuesCollection:
    print('=========================================')
    print('user: %s, timeRemaining: %sh, loggedEfforts: %sh' %(user, jiraIssuesCollection[user].getTimeRemaining(), jiraIssuesCollection[user].getLoggedEfforts()))
    for jiraIssue in jiraIssuesCollection[user].getJiraIssues():
        print(jiraIssue.key, jiraIssue.fields.customfield_39192)


def getTeamLoggedEffortsAndTimeRemaing(team):
    issues = jira.search_issues('cf[29790] =' + team +' AND project = LTE AND type=task \
        AND (updatedDate >= ' + currentFBStartDate + ' AND updatedDate <= ' + currentFBEndDate + ')' + ' ORDER BY assignee ASC', \
        maxResults=300)
    timeRemaining = 0
    loggedEfforts = 0
    for issue in issues:
        jiraIssue = jira.issue(issue.key, expand='changelog')
        # print(jiraIssue.key)
        timeRemaining += int(jiraIssue.fields.customfield_39192[:-1])
        # print(self.timeRemaining)
        for history in jiraIssue.changelog.histories:
            for item in history.items:
                # print(item.field)
                if item.field == 'Σ Logged Effort':
                    # print(history.created[:10])
                    historyCreatedTime = history.created[:10]
                    if historyCreatedTime >= currentFBStartDate and historyCreatedTime <= currentFBEndDate:
                        # print(item.fromString, item.toString)
                        if item.fromString != None:
                            loggedEfforts += int(item.toString[:-1]) - int(item.fromString[:-1])
                            # print('loggedEfforts %s' %loggedEfforts)

    return (timeRemaining, loggedEfforts)

teamCPFTH7=3645
teamTimeRemaining, teamLoggedEfforts = getTeamLoggedEffortsAndTimeRemaing(team='3645')
print('*****************************************')
print("teamLevel: (teamTimeRemaining %s, teamLoggedEfforts %s)" %(teamTimeRemaining, teamLoggedEfforts))

if teamTimeRemaining != personsTimeRemaining:
    print('unassigned efforts: %s' %(teamTimeRemaining - personsTimeRemaining))
    for jiraIssue in jiraIssuesCollection['unassigned'].getJiraIssues():
        print(jiraIssue.key, jiraIssue.fields.customfield_39192)